<template>
  <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" v-model="visible" width="500px" @close="handleClose">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" status-icon>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" :disabled="isEdit" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!isEdit">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
        <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="未知" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker
          v-model="form.birthDate"
          type="date"
          placeholder="选择出生日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="用户状态" prop="userStatus">
        <el-select v-model="form.userStatus" placeholder="请选择用户状态">
          <el-option label="禁用" :value="0" />
          <el-option label="正常" :value="1" />
          <el-option label="待验证" :value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false" :disabled="loading">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">{{ isEdit ? '保存' : '添加' }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: Boolean,
  isEdit: Boolean,
  userId: [Number, String],
  userData: Object
})
const emit = defineEmits(['update:visible', 'success'])

const visible = ref(props.visible)
watch(() => props.visible, v => visible.value = v)
watch(visible, v => emit('update:visible', v))

const formRef = ref()
const form = reactive({
  username: '',
  nickname: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  gender: 0,
  birthDate: '',
  userStatus: 1
})

const loading = ref(false)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度3-20位', trigger: 'blur' }
  ],
  nickname: [
    { required: false, message: '请输入昵称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度1-50位', trigger: 'blur' }
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value !== form.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }, trigger: 'blur' }
  ],
  gender: [
    { required: false, message: '请选择性别', trigger: 'change' }
  ],
  birthDate: [
    { required: false, message: '请选择出生日期', trigger: 'change' }
  ],
  userStatus: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ]
}

// 回显数据
watch(() => props.userData, (val) => {
  if (props.isEdit && val) {
    Object.assign(form, val)
    form.password = ''
    form.confirmPassword = ''
  } else if (!props.isEdit) {
    form.username = ''
    form.nickname = ''
    form.phone = ''
    form.email = ''
    form.password = ''
    form.confirmPassword = ''
    form.gender = 0
    form.birthDate = ''
    form.userStatus = 1
  }
}, { immediate: true })

const handleClose = () => {
  // 关闭弹窗时重置表单数据
  form.username = ''
  form.nickname = ''
  form.phone = ''
  form.email = ''
  form.password = ''
  form.confirmPassword = ''
  form.gender = 0
  form.birthDate = ''
  form.userStatus = 1
  
  // 清除验证状态
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  
  emit('update:visible', false)
}

const handleSubmit = () => {
  if (loading.value) return // 防止重复提交
  
  formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      // 新增时包含密码，编辑时不包含密码
      const submitData = { ...form }
      if (!props.isEdit) {
        // 新增用户：保留密码字段，但不提交确认密码字段
        delete submitData.confirmPassword
      } else {
        // 编辑用户：删除密码相关字段
        delete submitData.password
        delete submitData.confirmPassword
      }
      
      emit('success', submitData)
    } finally {
      loading.value = false
    }
  })
}
</script>
